<template>
  <el-dialog
    v-model="props.spareDialog"
    title="备件申领"
    :show-close="false"
    width="70%"
  >
    <div>备件选择</div>
    <el-row>
      <el-col :span="15" style="padding: 5px">
        <TableSearch :search="state.search" @search="onSearch" />
        <Table
          ref="tableRef"
          v-bind="state.tableData"
          class="table-demo"
          @pageChange="onTablePageChange"
          @listenClick="listenClick"
        >
          <template #default="{ slotData, slotColumn }">
            <div v-if="slotColumn.key === 'isSupport'">
              {{ slotData.isSupport }}
            </div>
          </template>
        </Table>
      </el-col>
      <el-col :span="9" style="padding: 5px">
        <div class="top">
          <div>已选择：{{ tableData.length }}个</div>
          <div
            style="cursor: pointer; color: var(--el-color-primary)"
            @click="empty"
          >
            清空
          </div>
        </div>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          row-key="partNum"
        >
          <el-table-column prop="partNum" label="备件编号" />
          <el-table-column prop="partName" label="备件名称" />
          <el-table-column prop="partTypeName" label="备件类型" />
          <el-table-column prop="num" label="申请数量">
            <template #default="scope">
              <el-input
                v-model="scope.row.num"
                autocomplete="off"
                placeholder="输入数量"
                @change="inputChange(scope.row)"
                type="text"
                maxlength="8"
                onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^123456789]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
                onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-19]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <div>
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" @click="submit()" :loading="loading">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, reactive, defineAsyncComponent, watch, computed } from 'vue'
import { verifiyNumberInteger } from '/@/utils/toolsValidate'
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const props = defineProps({
  spareDialog: Boolean,
  spareType: String
})
const emit = defineEmits(['saCancel', 'saSubmit'])

const tableData = ref<any>([])
const loading = ref<any>(false)

// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    empty: false, // 清除表格选择
    first: true,
    // 表头内容（必传，注意格式）
    header: [
      { key: 'partNum', colWidth: '', title: '设备编号', type: 'text' },
      { key: 'partName', colWidth: '', title: '设备名称', type: 'text' },
      { key: 'partTypeName', colWidth: '', title: '备件类型', type: 'text' },
      { key: 'realStock', colWidth: '', title: '备件库存', type: 'text' }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/devicePartRelevance/partRelevanceListAll',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: false, // 是否显示表格序号
      isSelection: true, // 是否显示表格多选
      isOperate: false, // 是否显示表格操作栏
      isExtend: false // 是否可以扩展
    },
    // 搜索参数
    param: {
      deviceType: '',
      inventoryFlag: 1
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入设备编号/名称搜索',
        type: 'input'
      }
    ]
  }
})

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}
// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  // console.log(state.tableData.param);
  state.tableData.flash = !state.tableData.flash
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}

const onSelectionChange = (val: any) => {
  tableData.value = val
  tableData.value.forEach((item: any) => {
    if (!item.num) {
      item.num = 1
    }
  })
}
const onSelect = (val: any) => {
  console.log(val)
}

const empty = () => {
  state.tableData.empty = !state.tableData.empty
}

const cancel = () => {
  empty()
  tableData.value = []
  emit('saCancel')
}

const inputChange = (val: any) => {
  tableData.value.forEach((i: any) => {
    if (i.id == val.id) {
      if (val.num > val.realStock) {
        ElMessage({
          type: 'warning',
          message: '申请数量不能大于库存数量'
        })
        val.num = ''
      }
    }
  })
}

const arr = ref<any>([])
const submit = () => {
  loading.value = true
  let flag = 0
  tableData.value.forEach((i: any) => {
    if (!i.num) {
      flag = 1
    } else {
      let obj = {
        partId: i.partId,
        amount: i.num
      }
      arr.value.push(obj)
      flag = 0
    }
  })
  if (flag == 1) {
    ElMessage.warning('备件申请数量不能为空！')
    loading.value = false
  } else {
    emit('saSubmit', arr.value)
    empty()
    tableData.value = []
    arr.value = []
    loading.value = false
  }
}

const emptyBack = () => {
  state.tableData.empty = !state.tableData.empty
}
const objFun = {
  onSelectionChange: onSelectionChange,
  onSelect: onSelect,
  emptyBack: emptyBack
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}

watch(
  () => props.spareDialog,
  () => {
    if (props.spareDialog == true) {
      state.tableData.param.deviceType = props.spareType
      getTableData()
    }
  }
)
</script>
<style scoped lang="scss">
.top {
  display: flex;
  justify-content: space-between;
}
</style>
